<?php
/**
 * Locale Helper
 *
 * @author Pavel Kovalyov
 */
class DateLocaler extends Zend_View_Helper_Abstract {

    private $_locale = null;

    public $datepickerDateFormat = '';
    public $zendFormat = '';

    public function dateLocaler($date){
        self::init();
        $zDate = new Zend_Date($date);
        $zDate->setLocale($this->_locale);
        return $zDate->get($this->zendFormat);
    }

    public function __construct($locale = null){
        if ($locale instanceof Zend_Locale) {
            $this->_locale = $locale;
        } elseif (is_string($locale)){
            if (Zend_Locale::isLocale($locale)) $this->_locale = new Zend_Locale($locale);
        }

        if (null !== $this->_locale){
            $this->zendFormat = Zend_Locale_Format::getDateFormat($this->_locale);
            $this->datepickerDateFormat = $this->resolveZendLocaleToDatePickerFormat($this->zendFormat);
        }
    }

    public function init(){
        
    }

    private function resolveZendLocaleToDatePickerFormat($format){
        $dateFormat = array(
            'EEEEE' => 'D', 'EEEE' => 'DD', 'EEE' => 'D', 'EE' => 'D', 'E' => 'D',
            'MMMM' => 'MM', 'MMM' => 'M', 'MM' => 'mm', 'M' => 'm',
            'YYYYY' => 'yy', 'YYYY' => 'yy', 'YYY' => 'yy', 'YY' => 'y', 'Y' => 'yy',
            'yyyyy' => 'yy', 'yyyy' => 'yy', 'yyy' => 'yy', 'yy' => 'y', 'y' => 'yy',
            'G' => '', 'e' => '', 'a' => '', 'h' => '', 'H' => '', 'm' => '',
            's' => '', 'S' => '', 'z' => '', 'Z' => '', 'A' => '',
        );

        $newFormat = "";
        $isText = false;
        $i = 0;
        while($i < strlen($format)) {
            $chr = $format[$i];
            if($chr == '"' || $chr == "'") {
                $isText = !$isText;
            }
            $replaced = false;
            if($isText == false) {
                foreach($dateFormat AS $zl => $jql) {
                    if(substr($format, $i, strlen($zl)) == $zl) {
                        $chr = $jql;
                        $i += strlen($zl);
                        $replaced = true;
                    }
                }
            }
            if($replaced == false) {
                $i++;
            }
            $newFormat .= $chr;
        }

        return $newFormat;
    }

}